// Multilingual support
const translations = {
  zh: {
    'nav-home': '首页',
    'nav-about': '关于我',
    'nav-projects': '项目',
    'nav-contact': '联系我',
    'home-title': '欢迎来到我的作品集',
    'home-subtitle': '创新设计与技术的完美结合',
    'home-projects': '查看我的项目',
    'home-about': '了解更多',
    'about-title': '关于我',
    'about-intro1': 'Python Developer，擅长消息中间件、实时数据处理、高可用架构设计。热爱技术探索，不断学习新知识以提升自身技能。在分布式系统和数据工程方面有丰富的实践经验。',
    'about-intro2': '工作之余，我喜欢Rust编程、收集幸运星、观看《孤独摇滚》和《摇曳露营》等动漫作品，这些爱好为我的开发工作带来了新的灵感。',
    'about-skills': '技能',
    'about-experience': '专业经历',
    'about-achievements': '个人成就',
    'about-achievements-list': [
      '清华大学优秀毕业生',
      '微软MVP',
      '华为开发者认证'
    ],
    'projects-title': '我的项目',
    'projects-subtitle': '项目1的详细描述。在这里介绍项目的主要功能、使用的技术栈和解决的问题。',
    'projects-subtitle2': '项目2的详细描述。在这里介绍项目的主要功能、使用的技术栈和解决的问题。',
    'projects-demo': '查看演示',
    'projects-source': '源代码',
    'contact-title': '联系我',
    'contact-intro': '如果您想与我合作或有任何问题，请随时联系我。我会尽快回复您！',
    'contact-name': '您的姓名',
    'contact-email': '您的邮箱',
    'contact-message': '您的消息',
    'contact-send': '发送消息',
    'contact-social': '其他联系方式',
    'contact-web': '个人网页',
    'contact-email-link': 'lindd_8321@qq.com',
    'contact-quick': '快速联系',
    'contact-期待': '期待与您合作，共同创造优秀的产品！',
    'footer-rights': '保留所有权利.',
    'footer-built': '使用现代技术构建',
    'skill-python': 'Python',
    'skill-mongodb': 'MongoDB',
    'skill-nextjs': 'Next.js',
    'skill-elasticsearch': 'ElasticSearch',
    'skill-rust': 'Rust',
    'edu-tsinghua-bachelor': '清华大学 - 本科',
    'edu-stanford-master': '斯坦福大学 - 硕士',
    'exp-google': 'Google - 软件工程师',
    'exp-openai': 'OpenAI - 软件工程师'
  },
  en: {
    'nav-home': 'Home',
    'nav-about': 'About',
    'nav-projects': 'Projects',
    'nav-contact': 'Contact',
    'home-title': 'Welcome to My Portfolio',
    'home-subtitle': 'The Perfect Combination of Innovative Design and Technology',
    'home-projects': 'View My Projects',
    'home-about': 'Learn More',
    'about-title': 'About Me',
    'about-intro1': 'Python Developer specializing in message middleware, real-time data processing, and high-availability architecture design. Passionate about technology exploration, constantly learning new knowledge to improve skills. Has rich practical experience in distributed systems and data engineering.',
    'about-intro2': 'In my spare time, I enjoy Rust programming, collecting Lucky Stars, watching anime such as "Bocchi the Rock" and "Yuru Camp", which bring new inspiration to my development work.',
    'about-skills': 'Skills',
    'about-experience': 'Professional Experience',
    'about-achievements': 'Personal Achievements',
    'about-achievements-list': [
      'Outstanding Graduate of Tsinghua University',
      'Microsoft MVP',
      'Huawei Developer Certification'
    ],
    'projects-title': 'My Projects',
    'projects-subtitle': 'Detailed description of Project 1. Introduce the main functions, technology stack used, and problems solved in the project here.',
    'projects-subtitle2': 'Detailed description of Project 2. Introduce the main functions, technology stack used, and problems solved in the project here.',
    'projects-demo': 'View Demo',
    'projects-source': 'Source Code',
    'contact-title': 'Contact Me',
    'contact-intro': 'If you want to collaborate with me or have any questions, please feel free to contact me. I will respond as soon as possible!',
    'contact-name': 'Your Name',
    'contact-email': 'Your Email',
    'contact-message': 'Your Message',
    'contact-send': 'Send Message',
    'contact-social': 'Other Contact Methods',
    'contact-web': 'Personal Website',
    'contact-email-link': 'lindd_8321@qq.com',
    'contact-quick': 'Quick Contact',
    'contact-期待': 'Looking forward to working with you to create excellent products!',
    'footer-rights': 'All rights reserved.',
    'footer-built': 'Built with modern technology',
    'skill-python': 'Python',
    'skill-mongodb': 'MongoDB',
    'skill-nextjs': 'Next.js',
    'skill-elasticsearch': 'ElasticSearch',
    'skill-rust': 'Rust',
    'edu-tsinghua-bachelor': 'Tsinghua University - Bachelor',
    'edu-stanford-master': 'Stanford University - Master',
    'exp-google': 'Google - Software Engineer',
    'exp-openai': 'OpenAI - Software Engineer'
  }
};

// Current language
let currentLang = localStorage.getItem('language') || 'zh';

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // Translation function
    function translatePage(lang) {
        // Update language switcher button text
        document.getElementById('current-lang').textContent = lang === 'zh' ? '中文' : 'EN';
        
        // Update all translatable elements
        const translatableElements = document.querySelectorAll('.translatable');
        translatableElements.forEach(element => {
            const key = element.getAttribute('data-key');
            if (translations[lang][key]) {
                element.textContent = translations[lang][key];
            }
        });
        
        // Update other elements that have specific keys
        const homeTitle = document.querySelector('#home h1');
        if (homeTitle) homeTitle.textContent = translations[lang]['home-title'];
        
        const homeSubtitle = document.querySelector('#home p');
        if (homeSubtitle) homeSubtitle.textContent = translations[lang]['home-subtitle'];
        
        const aboutTitle = document.querySelector('#about .section-title');
        if (aboutTitle) aboutTitle.textContent = translations[lang]['about-title'];
        
        // Update about section content
        const aboutIntro1 = document.querySelector('.about-text p:nth-child(3)'); // First intro paragraph
        if (aboutIntro1) aboutIntro1.textContent = translations[lang]['about-intro1'];
        
        const aboutIntro2 = document.querySelector('.about-text p:nth-child(4)'); // Second intro paragraph
        if (aboutIntro2) aboutIntro2.textContent = translations[lang]['about-intro2'];
        
        const skillsTitle = document.querySelector('.about-text .skills h3');
        if (skillsTitle) skillsTitle.textContent = translations[lang]['about-skills'];
        
        const experienceTitle = document.querySelector('.timeline h3');
        if (experienceTitle) experienceTitle.textContent = translations[lang]['about-experience'];
        
        const achievementsTitle = document.querySelector('.achievements h3');
        if (achievementsTitle) achievementsTitle.textContent = translations[lang]['about-achievements'];
        
        // Update achievements list
        const achievementItems = document.querySelectorAll('.achievements li');
        const achievementsList = translations[lang]['about-achievements-list'];
        if (achievementItems.length <= achievementsList.length) {
            for (let i = 0; i < achievementItems.length; i++) {
                if (achievementsList[i]) {
                    achievementItems[i].textContent = achievementsList[i];
                }
            }
        }
        
        const projectsTitle = document.querySelector('#projects .section-title');
        if (projectsTitle) projectsTitle.textContent = translations[lang]['projects-title'];
        
        const project1Desc = document.querySelector('#projects .project-card:nth-child(1) p');
        if (project1Desc) project1Desc.textContent = translations[lang]['projects-subtitle'];
        
        const project2Desc = document.querySelector('#projects .project-card:nth-child(2) p');
        if (project2Desc) project2Desc.textContent = translations[lang]['projects-subtitle2'];
        
        const project1Demo = document.querySelector('#projects .project-card:nth-child(1) .project-links a:first-child');
        if (project1Demo) project1Demo.textContent = translations[lang]['projects-demo'];
        
        const project1Source = document.querySelector('#projects .project-card:nth-child(1) .project-links a:last-child');
        if (project1Source) project1Source.textContent = translations[lang]['projects-source'];
        
        const project2Demo = document.querySelector('#projects .project-card:nth-child(2) .project-links a:first-child');
        if (project2Demo) project2Demo.textContent = translations[lang]['projects-demo'];
        
        const project2Source = document.querySelector('#projects .project-card:nth-child(2) .project-links a:last-child');
        if (project2Source) project2Source.textContent = translations[lang]['projects-source'];
        
        const contactTitle = document.querySelector('#contact .section-title');
        if (contactTitle) contactTitle.textContent = translations[lang]['contact-title'];
        
        const contactIntro = document.querySelector('#contact p');
        if (contactIntro) contactIntro.textContent = translations[lang]['contact-intro'];
        
        const contactNamePlaceholder = document.querySelector('#name');
        if (contactNamePlaceholder) contactNamePlaceholder.placeholder = translations[lang]['contact-name'];
        
        const contactEmailPlaceholder = document.querySelector('#email');
        if (contactEmailPlaceholder) contactEmailPlaceholder.placeholder = translations[lang]['contact-email'];
        
        const contactMessagePlaceholder = document.querySelector('#message');
        if (contactMessagePlaceholder) contactMessagePlaceholder.placeholder = translations[lang]['contact-message'];
        
        const contactSendBtn = document.querySelector('#contact-form .btn');
        if (contactSendBtn) contactSendBtn.textContent = translations[lang]['contact-send'];
        
        const contactSocialTitle = document.querySelector('.contact-info-section h3');
        if (contactSocialTitle) contactSocialTitle.textContent = translations[lang]['contact-social'];
        
        const contactWebSpan = document.querySelector('.social-links .social-link:first-child span');
        if (contactWebSpan) contactWebSpan.textContent = translations[lang]['contact-web'];
        
        const contactEmailSpan = document.querySelector('.social-links .social-link:last-child span');
        if (contactEmailSpan) contactEmailSpan.textContent = translations[lang]['contact-email-link'];
        
        const contactQuickTitle = document.querySelector('.contact-details h4');
        if (contactQuickTitle) contactQuickTitle.textContent = translations[lang]['contact-quick'];
        
        const contactQuickText = document.querySelector('.contact-details p');
        if (contactQuickText) contactQuickText.textContent = translations[lang]['contact-期待'];
        
        // Update skill badges
        const skillBadges = document.querySelectorAll('.skill-badge');
        if (skillBadges.length >= 5) {
            skillBadges[0].textContent = translations[lang]['skill-python'];
            skillBadges[1].textContent = translations[lang]['skill-mongodb'];
            skillBadges[2].textContent = translations[lang]['skill-nextjs'];
            skillBadges[3].textContent = translations[lang]['skill-elasticsearch'];
            skillBadges[4].textContent = translations[lang]['skill-rust'];
        }
        
        // Update timeline content
        const timelineItems = document.querySelectorAll('.timeline-item .timeline-content h4');
        if (timelineItems.length >= 4) {
            timelineItems[0].textContent = translations[lang]['edu-tsinghua-bachelor'];
            timelineItems[1].textContent = translations[lang]['edu-stanford-master'];
            timelineItems[2].textContent = translations[lang]['exp-google'];
            timelineItems[3].textContent = translations[lang]['exp-openai'];
        }
        
        // Update home links
        const homeLinks = document.querySelectorAll('.apple-link');
        if (homeLinks.length >= 2) {
            homeLinks[0].textContent = translations[lang]['home-projects'];
            homeLinks[1].textContent = translations[lang]['home-about'];
        }
        
        // Update footer
        const footerRights = document.querySelector('footer p:first-child');
        if (footerRights) {
            const year = new Date().getFullYear();
            // Extract the name from the current text (before translation)
            const currentText = footerRights.textContent || "© 2025 [您的名字]. 保留所有权利.";
            const nameMatch = currentText.match(/© \d{4} (.+?)\./);
            if (nameMatch) {
                footerRights.innerHTML = `&copy; ${year} ${nameMatch[1]}. ${translations[lang]['footer-rights']}`;
            } else {
                // Fallback if regex doesn't match
                footerRights.innerHTML = `&copy; ${year} [您的名字]. ${translations[lang]['footer-rights']}`;
            }
        }
        
        const footerBuilt = document.querySelector('footer p:last-child');
        if (footerBuilt) footerBuilt.textContent = translations[lang]['footer-built'];
    }
    
    // Initialize the page with the current language
    translatePage(currentLang);
    
    // Language switcher functionality
    const langToggle = document.getElementById('langToggle');
    const langMenu = document.getElementById('langMenu');
    const langOptions = document.querySelectorAll('.lang-option');
    
    // Toggle language menu
    langToggle.addEventListener('click', function(e) {
        e.stopPropagation();
        langMenu.classList.toggle('open');
        langToggle.classList.toggle('open');
    });
    
    // Close language menu when clicking elsewhere
    document.addEventListener('click', function(e) {
        if (!langToggle.contains(e.target)) {
            langMenu.classList.remove('open');
            langToggle.classList.remove('open');
        }
    });
    
    // Language selection
    langOptions.forEach(option => {
        option.addEventListener('click', function(e) {
            e.preventDefault();
            const selectedLang = this.getAttribute('data-lang');
            
            if (selectedLang !== currentLang) {
                currentLang = selectedLang;
                localStorage.setItem('language', currentLang);
                translatePage(currentLang);
                
                // Close the menu after selection
                langMenu.classList.remove('open');
                langToggle.classList.remove('open');
            }
        });
    });
    
    // 移动端菜单切换
    const menuToggle = document.getElementById('menuToggle');
    const navMenu = document.getElementById('navMenu');
    
    if (menuToggle && navMenu) {
        menuToggle.addEventListener('click', function() {
            navMenu.classList.toggle('open');
            
            // 汉堡菜单动画
            const spans = menuToggle.querySelectorAll('span');
            if (navMenu.classList.contains('open')) {
                spans[0].style.transform = 'rotate(45deg) translate(5px, 5px)';
                spans[1].style.opacity = '0';
                spans[2].style.transform = 'rotate(-45deg) translate(7px, -6px)';
            } else {
                spans[0].style.transform = 'none';
                spans[1].style.opacity = '1';
                spans[2].style.transform = 'none';
            }
        });
        
        // 点击导航链接后关闭菜单
        const navLinks = navMenu.querySelectorAll('a');
        navLinks.forEach(link => {
            link.addEventListener('click', () => {
                navMenu.classList.remove('open');
                const spans = menuToggle.querySelectorAll('span');
                spans[0].style.transform = 'none';
                spans[1].style.opacity = '1';
                spans[2].style.transform = 'none';
            });
        });
    }
    
    // 滚动时header样式变化
    const header = document.querySelector('header');
    const nav = document.querySelector('nav');
    
    window.addEventListener('scroll', function() {
        if (window.scrollY > 50) {
            header.classList.add('scrolled');
            nav.classList.add('scrolled');
        } else {
            header.classList.remove('scrolled');
            nav.classList.remove('scrolled');
        }
    });
    
    // 导航激活状态管理
    const navLinks = document.querySelectorAll('nav a');
    const sections = document.querySelectorAll('section');
    
    // 设置当前激活的导航项
    function setActiveLink() {
        let current = '';
        
        sections.forEach(section => {
            const sectionTop = section.offsetTop;
            if (scrollY >= sectionTop - 100) {
                current = section.getAttribute('id');
            }
        });
        
        navLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href') === `#${current}`) {
                link.classList.add('active');
            }
        });
    }
    
    // 导航链接点击处理
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 更新激活状态
            navLinks.forEach(l => l.classList.remove('active'));
            this.classList.add('active');
            
            const targetId = this.getAttribute('href');
            const targetSection = document.querySelector(targetId);
            
            if (targetSection) {
                window.scrollTo({
                    top: targetSection.offsetTop - 80, // 考虑固定导航的高度
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // 滚动时更新导航激活状态
    window.addEventListener('scroll', setActiveLink);
    
    // 表单提交处理
    const contactForm = document.getElementById('contact-form');
    
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const name = document.getElementById('name').value;
            const email = document.getElementById('email').value;
            const subject = document.getElementById('subject').value;
            const message = document.getElementById('message').value;
            
            // 简单验证
            if (name && email && message) {
                // 创建成功消息
                const successMessage = document.createElement('div');
                successMessage.textContent = `感谢您的消息，${name}！我会尽快回复您。`;
                successMessage.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: #28a745;
                    color: white;
                    padding: 15px 20px;
                    border-radius: 8px;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                    z-index: 10000;
                    animation: slideIn 0.3s ease;
                `;
                
                // 添加动画样式
                if (!document.getElementById('form-success-styles')) {
                    const style = document.createElement('style');
                    style.id = 'form-success-styles';
                    style.textContent = `
                        @keyframes slideIn {
                            from { transform: translateX(100%); opacity: 0; }
                            to { transform: translateX(0); opacity: 1; }
                        }
                        @keyframes slideOut {
                            from { transform: translateX(0); opacity: 1; }
                            to { transform: translateX(100%); opacity: 0; }
                        }
                    `;
                    document.head.appendChild(style);
                }
                
                document.body.appendChild(successMessage);
                
                // 3秒后移除消息
                setTimeout(() => {
                    successMessage.style.animation = 'slideOut 0.3s ease';
                    setTimeout(() => {
                        document.body.removeChild(successMessage);
                    }, 300);
                }, 3000);
                
                // 重置表单
                contactForm.reset();
            } else {
                // 创建错误消息
                const errorMessage = document.createElement('div');
                errorMessage.textContent = '请填写所有必填字段。';
                errorMessage.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: #dc3545;
                    color: white;
                    padding: 15px 20px;
                    border-radius: 8px;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                    z-index: 10000;
                    animation: slideIn 0.3s ease;
                `;
                
                document.body.appendChild(errorMessage);
                
                // 3秒后移除消息
                setTimeout(() => {
                    errorMessage.style.animation = 'slideOut 0.3s ease';
                    setTimeout(() => {
                        document.body.removeChild(errorMessage);
                    }, 300);
                }, 3000);
            }
        });
        
        // 表单输入动画效果
        const formControls = contactForm.querySelectorAll('.form-control');
        formControls.forEach(control => {
            // 添加聚焦效果
            control.addEventListener('focus', function() {
                this.parentElement.style.transform = 'scale(1.02)';
            });
            
            // 添加失焦效果
            control.addEventListener('blur', function() {
                this.parentElement.style.transform = 'scale(1)';
            });
            
            // 添加悬停效果
            control.addEventListener('mouseenter', function() {
                this.style.boxShadow = '0 0 0 2px var(--primary-color)';
            });
            
            control.addEventListener('mouseleave', function() {
                if (document.activeElement !== this) {
                    this.style.boxShadow = 'none';
                }
            });
        });
    }
    
    // 添加项目卡片悬停效果
    const projectCards = document.querySelectorAll('.project-card');
    
    projectCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-10px)';
            this.style.boxShadow = '0 15px 30px rgba(0,0,0,0.15)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)';
        });
    });
    
    // 添加按钮点击效果
    const buttons = document.querySelectorAll('.btn');
    
    buttons.forEach(button => {
        button.addEventListener('mousedown', function() {
            this.style.transform = 'translateY(-1px)';
            this.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)';
        });
        
        button.addEventListener('mouseup', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)';
        });
        
        button.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)';
        });
    });
    
    // Apple风格的链接悬停效果
    const appleLinks = document.querySelectorAll('.apple-link');
    
    appleLinks.forEach(link => {
        link.addEventListener('mouseenter', function() {
            this.style.opacity = '0.8';
        });
        
        link.addEventListener('mouseleave', function() {
            this.style.opacity = '1';
        });
    });
    
    // 关于我部分的动画效果
    const aboutImage = document.querySelector('.about-image');
    const skillBadges = document.querySelectorAll('.skill-badge');
    
    if (aboutImage) {
        aboutImage.addEventListener('mouseenter', function() {
            this.style.transform = 'scale(1.05)';
        });
        
        aboutImage.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1)';
        });
    }
    
    // 技能标签的随机动画延迟
    skillBadges.forEach((badge, index) => {
        badge.style.animationDelay = `${index * 0.1}s`;
    });
    
    // 联系部分粒子效果
    const particles = document.querySelectorAll('.particle');
    
    particles.forEach((particle, index) => {
        // 随机初始位置
        const randomX = Math.random() * 100;
        const randomY = Math.random() * 100;
        particle.style.left = `${randomX}%`;
        particle.style.top = `${randomY}%`;
        
        // 随机动画延迟
        particle.style.animationDelay = `${index * 0.5}s`;
    });
    
    // 控制台消息
    console.log('个人作品集网站已加载！');
    console.log('欢迎访问我的作品集网站！');
});

// 一个简单的函数示例
function showMessage(message) {
    alert(message);
}

// 平滑滚动函数
function smoothScroll(target, duration) {
    const targetElement = document.querySelector(target);
    const targetPosition = targetElement.offsetTop - 80;
    const startPosition = window.pageYOffset;
    const distance = targetPosition - startPosition;
    let startTime = null;
    
    function animation(currentTime) {
        if (startTime === null) startTime = currentTime;
        const timeElapsed = currentTime - startTime;
        const run = ease(timeElapsed, startPosition, distance, duration);
        window.scrollTo(0, run);
        if (timeElapsed < duration) requestAnimationFrame(animation);
    }
    
    function ease(t, b, c, d) {
        t /= d / 2;
        if (t < 1) return c / 2 * t * t + b;
        t--;
        return -c / 2 * (t * (t - 2) - 1) + b;
    }
    
    requestAnimationFrame(animation);
}